﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;

namespace SimpleText.Framework
{

	public class TextDefinitionGroup
	{
		public TextDefinitionGroup()
		{
			TextDefinitions = new Dictionary<string, TextDefinition>();
		}

		public string Name { get; set; }
		public Dictionary<string, TextDefinition> TextDefinitions { get; set; }
		public string Source { get; set; }
		public string Comment { get; set; }
		public string TranslatorComment { get; set; }

		/// <summary>
		/// String indexer (uses the text definition name)
		/// </summary>
		public TextDefinition this[string textDefinitionName]
		{
			get
			{
				if (TextDefinitions.ContainsKey(textDefinitionName))
				{
					return TextDefinitions[textDefinitionName]; 
				}
				else
				{
					return null;
				}
			}
			set
			{
				TextDefinitions[textDefinitionName] = value;
			}
		}

		public void InitWithXml(XmlNode xmlNode)
		{
			Name = xmlNode.Attributes["name"].Value;
			XmlNode commentNode = xmlNode.SelectSingleNode("comment");
			XmlNode translatorCommentNode = xmlNode.SelectSingleNode("translatorComment");
			XmlNode sourceNode = xmlNode.SelectSingleNode("source");
			if (commentNode != null)
			{
				Comment = commentNode.InnerText;
			}
			if (translatorCommentNode != null)
			{
				TranslatorComment = translatorCommentNode.InnerText;
			}
			if (sourceNode != null)
			{
				Source = sourceNode.InnerText;
			}
			foreach (XmlNode textDefNode in xmlNode.SelectNodes("textDefinitions/textDefinition"))
			{
				TextDefinition newTextDef = new TextDefinition();
				newTextDef.InitWithXml(textDefNode);
				TextDefinitions[newTextDef.Name] = newTextDef;
			}
		}

		public string GetAsXml()
		{
			return GetAsXml("");
		}

		public string GetAsXml(string baseIndent)
		{
			string indent = "\t";
			string xml = "";

			xml += baseIndent + "<textDefinitionGroup name=\"" + Name + "\">" + "\r\n";

			if (!String.IsNullOrEmpty(Comment))
			{
				xml += baseIndent + indent + "<comment><![CDATA[" + Comment + "]]></comment>" + "\r\n";
			}
			if (!String.IsNullOrEmpty(TranslatorComment))
			{
				xml += baseIndent + indent + "<translatorComment><![CDATA[" + TranslatorComment + "]]></translatorComment>" + "\r\n";
			}
			if (!String.IsNullOrEmpty(Source))
			{
				xml += baseIndent + indent + "<source><![CDATA[" + Source + "]]></source>" + "\r\n";
			}

			xml += baseIndent + indent + "<textDefinitions>" + "\r\n";
			foreach (TextDefinition textDefinition in TextDefinitions.Values)
			{
				xml += textDefinition.GetAsXml(baseIndent + indent + "\t") + "\r\n";
			}
			xml += baseIndent + indent + "</textDefinitions>" + "\r\n";
			xml += baseIndent + "</textDefinitionGroup>" + "\r\n";

			return xml;
		}

	}
}